package main

import (
	"github.com/garyburd/redigo/redis"
	"fmt"
	"time"
	"strconv"
)

func ConnectRedis() (redis.Conn){

	config := GetConfig()

	conn, err := redis.Dial("tcp", config.Redis.Hosts[0])
	if err != nil {
		fmt.Println(err)
	}

	return conn
}


func SetRedis(key string,value string) (interface{}){

	conn := ConnectRedis()

	defer conn.Close()

	result,err := conn.Do("SET", key,value)
	if err != nil {
		fmt.Println(err)
	}
	return result
}

func GetRedis(key string) string{

	conn := ConnectRedis()

	defer conn.Close()

	result, err := redis.String(conn.Do("GET", key))
	if err != nil {
		fmt.Println(err)
	}
	return result
}

func DelRedis(key string) bool{

	conn := ConnectRedis()

	defer conn.Close()

	delResult, err := redis.Int(conn.Do("DEL", key))
	if err != nil {
		fmt.Println(err)
	}
	if delResult > 0{
		return true
	}
	return false
}

func Setnx(key string,value string)  bool{

	conn := ConnectRedis()

	defer conn.Close()

	result, err := redis.Bool(conn.Do("SETNX", key,value))
	if err != nil {
		fmt.Println(err)
	}
	//if result.(int) == 0 {
	//	return false
	//}
	//return true

	return result
}

func GetLockKey(JobId string,lockType string) string{
	LockKey := "job_center_" + DockerId + "_" + lockType + "" + JobId

	return LockKey
}


func JobLock(jobId string,TimeOut int64,lockType string) int64{
	LockKey := GetLockKey(jobId,lockType)

	NowTime := time.Now().Unix()
	Lock := NowTime

	result := Setnx(LockKey,strconv.FormatInt(NowTime,10))


	if result == false {
		StrLockTime := GetRedis(LockKey)
		LockTime,_ := strconv.ParseInt(StrLockTime, 10, 64)

		if NowTime-LockTime > TimeOut{
			result := SetRedis(LockKey,strconv.FormatInt(NowTime,10))
			if result != "OK"{
				Lock = 0
			}
		}else{
			Lock = 0
		}
	}
	return Lock
}



func JobUnLock(jobId string,TheLockTime int64,lockType string) bool{
	LockKey := GetLockKey(jobId,lockType)

	StrLockTime := GetRedis(LockKey)
	LockTime,_ := strconv.ParseInt(StrLockTime, 10, 64)
	if TheLockTime != LockTime{
		return false
	}
	return DelRedis(LockKey)
}